package com.domain.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.domain.common.AppLogger;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.ContactsMapper;
import com.domain.dao.UsersAddFriendsMapper;
import com.domain.dao.UsersMapper;
import com.domain.dao.UsersRelationshipMapper;
import com.domain.pojo.Contacts;
import com.domain.pojo.Users;
import com.domain.pojo.UsersAddFriends;
import com.domain.pojo.UsersRelationship;
import com.domain.service.ContactsService;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.message.SmsChuangLan;
import com.domain.utils.message.chuanglan.SmsVariableResponse;
import com.domain.utils.wyyx.IMSet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class ContactsServiceImpl implements ContactsService {

    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(ContactsServiceImpl.class.getSimpleName(), Level.INFO.toString(), true);

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UsersAddFriendsMapper usersAddFriendsMapper;

    @Autowired
    private UsersRelationshipMapper usersRelationshipMapper;


    /**
     * 同步通讯录
     *
     * @param userId
     * @param jsonStr
     * @return
     */
    @Override
    public Result synchronizationContacts(String userId, String jsonStr) throws IOException {
        logger.info("获取的jsonStr" + jsonStr);
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(jsonArray.getString(i));
            //获取通讯录好友名称
            String name = (String) jsonObject.get("name");
            //获取好友得电话号码
            String phoneNums = jsonObject.get("number").toString();
            //用户信息
            Users usersse = usersMapper.selectByPrimaryKey(userId);
            //验证手机号
            /* if (NotNullUtils.isMobile(phoneNums)) {*/
            //根据手机号查看是否注册app
            Users user = usersMapper.selectByUserPhone(phoneNums);
            //判断用户得通讯录是否有该手机号
            Contacts contactsList = contactsMapper.selectByNameAndPhoneNum(phoneNums, userId);
            if (!NotNullUtils.isNotNullObject(contactsList)) {
                //判断是否是自己的手机号
                if (!usersse.getPhone().equals(phoneNums)) {
                    Contacts c = new Contacts();
                    c.setId(UUIDUtils.getRandomUUID());
                    c.setCreatTime(new Date());
                    c.setUserId(userId);
                    if (NotNullUtils.isNotNullObject(user)) {
                        //添加app好友
                        c.setType(Comments.CONTACTS_APP_);
                        c.setSpareOne(user.getPhone());
                        c.setSpareTwo(user.getId());
                        c.setName(user.getName());
                        c.setHeadImage(user.getHeadImage());
                        c.setItisFillter(Comments.IT_IS_FILLTER_NO);
                       /* //添加人脉关系（树形结构）
                        addUsersRelationship(userId, user.getId());*/
                        //设置网易云信好友
                        IMSet.addFriend(userId, user.getId(), "1", "");
                    } else {
                        //添加通讯录好友
                        c.setName(name);
                        c.setHeadImage(Const.USER_HEAD_IMAGE);
                        c.setType(Comments.CONTACTS);
                        c.setItisFillter(Comments.IT_IS_FILLTER_NO);
                        c.setSpareOne(phoneNums);
                    }
                    contactsMapper.insertSelective(c);
                }
            }
            /*}*/
        }
        return Result.success();
    }


    /**
     * 生成人脉链关系 （树形结构）
     */

    private void addUsersRelationship(String usersId, String friendsId) {
        UsersRelationship ufr = new UsersRelationship();
        ufr.setId(friendsId);
        ufr.setPrentId(usersId);
        ufr.setCreatTime(new Date());
        usersRelationshipMapper.insertSelective(ufr);
    }


    /**
     * 获取通讯录列表(搜索项)
     *
     * @param userId   用户id
     * @param phoneNum 电话号码
     * @param name     真实姓名
     * @param pageNum  页码
     * @param pageSize 每页显示的长度
     * @return
     */
    //只读事务
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getContactsList(String userId, String phoneNum, String name, String pageNum, String pageSize) {
        /*  PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));*/
        Map<String, Object> map = new HashMap<>();
        if (NotNullUtils.isNotNullObject(name)) {
            map.put("name", name);
        }
        if (NotNullUtils.isNotNullObject(phoneNum)) {
            map.put("phoneNum", phoneNum);
        }
        map.put("userId", userId);
        List<Contacts> contactsList = contactsMapper.selectByUserId(map);
        /*  PageInfo pageInfo = new PageInfo(contactsList);*/
        return Result.success("操作成功", contactsList);
    }

    /**
     * 获取加好友请求列表
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    //只读事务
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getNewFriendsRequestList(String userId, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Map<String, Object>> friends = usersAddFriendsMapper.selectByUsersId(userId);
        PageInfo pageInfo = new PageInfo(friends);
        return Result.success("操作成功", pageInfo.getList());
    }

    /**
     * 同意加好友
     *
     * @param userId    用户id
     * @param friendsId 好友id(请求加好友的id)
     * @return
     */
    @Override
    public Result agreeAddFriends(String addFriedndsId, String userId, String friendsId) {
        Users u = usersMapper.selectByPrimaryKey(friendsId);
        //增加好友通讯录
        Contacts c = new Contacts();
        c.setId(UUIDUtils.getRandomUUID());
        c.setHeadImage(u.getHeadImage());
        c.setName(u.getName());
        c.setType(Comments.CONTACTS_APP_);
        c.setSpareOne(u.getPhone());
        c.setSpareTwo(u.getId());
        c.setCreatTime(new Date());
        c.setUserId(userId);
        contactsMapper.insertSelective(c);
        //修改请求记录状态
        UsersAddFriends us = new UsersAddFriends();
        us.setId(addFriedndsId);
        us.setType(Const.AGREE_FRIENDS);
        usersAddFriendsMapper.updateByPrimaryKeySelective(us);
        return Result.success("操作成功");
    }

    /**
     * 邀请好友发短信
     *
     * @param userId   用户id
     * @param phoneNum 手机号
     * @return
     */
    @Override
    public Result joinAppSendMesssage(String userId, String phoneNum) {
        Users users = usersMapper.selectByPrimaryKey(userId);
        SmsVariableResponse response = SmsChuangLan.sendMessage(phoneNum, users.getName(), "1");
        Map<String, Object> maps = new HashMap<>();
        if (response.getSuccessNum().equals("1")) {
            //修改时间
            Contacts c = contactsMapper.selectByusersIdAndPhoneNum(userId, phoneNum);
            if (NotNullUtils.isNotNullObject(c)) {
                c.setSendsmsTime(new Date());
                contactsMapper.updateByPrimaryKey(c);
            }
            maps.put("code", response.getSuccessNum());
            maps.put("desc", "短信发送成功");
        }
        return Result.success(maps);
    }

    /**
     * 忽略加好友
     *
     * @param uafId
     * @return
     */
    @Override
    public Result deleteAddFriends(String uafId) {
        usersAddFriendsMapper.deleteByPrimaryKey(uafId);
        return Result.success();
    }


}
